package com.meiqiang.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ThreadTest {

    public static void main(String[] args) throws Exception {
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程: " + Thread.currentThread().getName());
//            int i = 10 / 0;
//            System.out.println("运行结果" + i);
//            return i;
//        }).whenComplete((r, e) -> {
//            System.out.println("异步任务成功完成了,结果是："+r);
//        }).exceptionally(throwable -> {
//            throwable.printStackTrace();
//            return 10;
//        });

//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            System.out.println("当前线程: " + Thread.currentThread().getName());
//            int i = 10 / 0;
//            System.out.println("运行结果" + i);
//            return i;
//        }).handle((res,ex)->{
//            return 0;
//        });
        /**
         * 线程串行化
         * 1.thenRunAsync 不能获取返回值
         * thenRunAsync(()->{
         *             System.out.println("任务2执行了");
         *         });
         *  2.thenAcceptAsync 能接收上一步结果，但是无返回值
         *  thenAcceptAsync(res->{
         *             System.out.println("任务2执行了");
         *         });
         *  3.thenApplyAsync 能接收上一步的结果，有返回值
         *  thenApplyAsync(res->{
         *             System.out.println("任务2执行了"+res);
         *             return "hello"+res;
         */
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程: " + Thread.currentThread().getName());
            int i = 10 / 2;
            System.out.println("运行结果" + i);
            return i;
        }).thenApplyAsync(res->{
            System.out.println("任务2执行了"+res);
            return "hello"+res;
        });
        System.out.println("===="+future.get());
    }
}
